import memo from '../common/wrapMemo';
import { Tree, Button, Space, message } from 'antd';
import React, { useState, useEffect } from 'react';
import style from './LayerManage.module.scss';
import { CloseOutlined } from '@ant-design/icons';
import { Scrollbars } from 'react-custom-scrollbars';
import Loading from '../common/Loading';
import api from '../../api/index';
import ImportModal from './ImportModal';
import ExportModal from './ExportModal';

const LayerManage = memo((props) => {
    const { onClose, userInfo } = props;
    const [checkedKeys, setCheckedKeys] = useState([]);
    const [checkedNodes, setCheckNodes] = useState([]);
    const [modal, setModal] = useState();
    const [treeDatas, setTreeDatas] = useState([]); // 图层列表树
    const [treeLoading, setTreeLoading] = useState(false);
    const [loading, setLoading] = useState(false);

    useEffect(async () => {
        queryTreeData();
    }, []);

    const queryTreeData = async () => {
        // 获取图层列表
        setCheckNodes([]);
        setCheckedKeys([]);
        setTreeLoading(true);

        api.search.queryLayerTree().then((res) => {
            const {code, data} = res.data;
            if(code === 200){
                const treeData = generateTreeData(data);
                setTreeDatas(treeData);
            }
        }).catch(err => {
            console.log(err);
        }).finally(() => {
            setTreeLoading(false);
        })
    };

    // 构造图层树数据
    const generateTreeData = (groups) => {
        let treeDatas = [];

        const recursive = (treeChildren, key, datas) => {
            datas.forEach((data) => {
                let childrenData = {}; 
                const {name, code, isClassify, fields} = data;
                childrenData['title'] = name;
                childrenData['key'] = `${key}-${code}`;
                childrenData['isClassify'] = isClassify;
                childrenData['fields'] = fields;
                if(data['children']){
                    childrenData['children'] = [];
                    recursive(childrenData.children, childrenData['key'], data['children']);
                }
                treeChildren.push(childrenData);
            });
        };

        recursive(treeDatas, 0, groups);

        return treeDatas;
    };

    const onCheck = (checkedKeys, e) => {
        setCheckedKeys(checkedKeys);
        setCheckNodes(e.checkedNodes);
    };

    // 删除数据
    const deleteData = () => {
        const userName = userInfo.get('userName');
        const checkLeafs = checkedNodes.filter((item) => {
            return (!item.children || item.children.length === 0)
        });
        let status = {};
        checkLeafs.forEach((leaf) => {
            const { key, title } = leaf;

            const arr = key.split('-');
            api.layer
                .modifyLayer({
                    groupId: arr[0],
                    mapId: arr[1],
                    layerId: arr[2],
                    userName,
                    layerName: title,
                })
                .then((res) => {
                    if (res?.data?.infocode === 10000) {
                        status[key] = true;
                    } else {
                        status[key] = false;
                    }
                })
                .finally(() => {
                    if (Object.keys(status).length === checkLeafs.length) {
                        if (Object.values(status).every((item) => !!item)) {
                            message.success('删除成功');
                        } else if (Object.values(status).every((item) => !item)) {
                            message.error('删除失败');
                        } else {
                            const successCount = Object.values(status).filter((item) => !!item)
                                .length;
                            const failCount = Object.values(status).filter((item) => !item).length;
                            message.success(`删除成功${successCount}个,删除失败${failCount}个`);
                        }

                        queryTreeData();
                        setModal(false);
                    }
                });
        });
    };

    // 导出数据
    const exportData = ({ exportType }) => {
        let layerNames = checkedNodes.filter((item) => !item.children).map((item) => item.title);
        layerNames = [...new Set(layerNames)];
        setLoading(true);
        const url = `/webapi/authority/downloadfile?layerName=${layerNames.join(
            ','
        )}&type=${exportType}&userName=${userInfo.get('userName')}`;

        // getBlob(url).then((blob) => {
        //     saveAs(blob);
        // });
        const anchor = document.createElement('a');
        // const fileName = fileName || 'download';
        if ('download' in anchor) {
            anchor.href = url;
            // anchor.setAttribute('download', fileName);
            // anchor.innerHTML = 'downloading...';
            anchor.style.display = 'none';
            document.body.appendChild(anchor);
            setTimeout(function () {
                anchor.click();
                document.body.removeChild(anchor);
                setLoading(false);
                setModal('');
                message.info('导出中...');
            }, 66);
        }
        // api.layer
        //     .exportFile({
        //         layerName: layerNames.join(','),
        //         type: exportType,
        //         userName: userInfo.get('userName'),
        //     })
        //     .then((res) => {
        //         const link = document.createElement('a');
        //         let blob = new Blob([res.data], { type: 'application/vnd.ms-excel' });
        //         link.style.display = 'none';
        //         link.href = URL.createObjectURL(blob);

        //         // link.download = res.headers['content-disposition'] //下载后文件名
        //         link.download = layerNames.join(',');
        //         document.body.appendChild(link);
        //         link.click();
        //         document.body.removeChild(link);
        //         setLoading(false);
        //     });
    };
    //通过文件下载url拿到对应的blob对象
    // const getBlob = (url) => {
    //     return new Promise((resolve) => {
    //         const xhr = new XMLHttpRequest();
    //         xhr.open('GET', url, true);
    //         xhr.responseType = 'blob';
    //         xhr.onload = () => {
    //             //取出下载文件名
    //             const name = xhr.getResponseHeader('content-disposition');
    //             const fileName = name.substring(name.lastIndexOf('=') + 1, name.length);
    //             const downloadFile = decodeURIComponent(fileName);
    //             console.log(downloadFile);

    //             if (xhr.status === 200) {
    //                 resolve(xhr.response);
    //             }
    //         };

    //         xhr.send();
    //     });
    // };

    // 下载文件js模拟点击a标签进行下载
    // const saveAs = (blob) => {
    //     var link = document.createElement('a');
    //     link.href = window.URL.createObjectURL(blob);
    //     // link.download = filename;
    //     link.click();
    // };

    // 导入数据
    const importData = () => {};

    return (
        <>
            <div className={style.layerManage}>
                <div className={style.head}>
                    <span>图层管理</span>
                    <CloseOutlined onClick={onClose} />
                </div>
                {treeLoading ? (
                    <Loading />
                ) : (
                    <Scrollbars autoHeight autoHeightMin={0} autoHeightMax={`520px`}>
                        <Tree
                            className={style.tree}
                            checkable
                            selectable={false}
                            onCheck={onCheck}
                            checkedKeys={checkedKeys}
                            treeData={treeDatas}
                            defaultExpandAll={false}
                        />
                    </Scrollbars>
                )}

                <div className={style.footer}>
                    <Space size="middle">
                        <Button className={style.rejectBtn} onClick={() => setModal('delete')}>
                            删除数据
                        </Button>
                        <Button className={style.resetUserBtn} onClick={() => setModal('export')}>
                            导出数据
                        </Button>
                        <Button className={style.passBtn} onClick={() => setModal('import')}>
                            导入数据
                        </Button>
                    </Space>
                </div>
            </div>
            {modal === 'delete' && (
                <div className={style.deleteModal}>
                    <CloseOutlined onClick={() => setModal('')} className={style.close} />
                    <div className={style.content}>
                        <span className={`${style.warnIcon} iconfont icon-warning`}></span>
                        <span>是否删除数据？</span>
                        <Button className={style.rejectBtn} onClick={deleteData}>
                            删除
                        </Button>
                    </div>
                </div>
            )}
            {modal === 'export' && (
                <ExportModal
                    onClose={() => setModal('')}
                    exportData={exportData}
                    disabled={checkedNodes?.length === 0}
                    loading={loading}
                />
            )}
            {modal === 'import' && (
                <ImportModal
                    layers={treeDatas}
                    userInfo={userInfo}
                    onClose={() => {
                        setModal('');
                        queryTreeData();
                    }}
                    importData={importData}
                />
            )}
        </>
    );
});
export default LayerManage;
